package com.example.xinyun.slice;

import com.bumptech.glide.Glide;
import com.example.xinyun.MyApplication;
import com.example.xinyun.ResourceTable;
import com.example.xinyun.domain.UrlContant;
import com.example.xinyun.db.TbFourmList;
import com.example.xinyun.db.TbTzRequestBean;
import com.example.xinyun.utils.ImageUtils;
import com.example.xinyun.utils.UilImageLoader;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridAbility;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import id.zelory.compressor.Compressor;
import id.zelory.compressor.constraint.CompressFormat;
import id.zelory.compressor.constraint.Compression;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.camera.device.CameraAbility;
import ohos.media.image.ImageSource;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FbAbilitySlice extends AbilitySlice {
    public static final int REQUEST_CODE_CHOOSE = 1001;
    private List<Uri> mSelected;
    private String imagepath = "";
    private ImagePicker imagePicker;
    private ArrayList<ImageItem> images = new ArrayList<>();
    private Image mt3;
    private TextField mt1, mt2;
    private File mfile;
    private String imagename;

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        images = resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);


        if (images.size() != 0) {
            Glide.with(this).load(images.get(0).uriSchema).into(mt3);
            imagepath = images.get(0).uriSchema;
            imagename = images.get(0).name;
        }
    }


    private final EventHandler myEventHandler =
            new EventHandler(EventRunner.getMainEventRunner()) {
                @Override
                protected void processEvent(InnerEvent event) {
                    super.processEvent(event);

                    switch (event.eventId) {
                        case 0:
                            new ToastDialog(getAbility())
                                    .setText("发布成功")
                                    .show();
                            getAbility().terminateAbility();
                            break;
                        case 1:
                            new ToastDialog(getAbility())
                                    .setText("发布失败")
                                    .show();
                            break;
                        default:
                            break;
                    }
                }
            };


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_fb);
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_MEDIA",
                "ohos.permission.WRITE_MEDIA",
                "ohos.permission.MEDIA_LOCATION",
                "ohos.permission.CAMERA",
                "ohos.permission.WRITE_USER_STORAGE"}, 1);

        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(config); // UniversalImageLoader初始化
        ImagePicker.setTakePhotoAbility(CameraAbility.class);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new UilImageLoader()); // 设置图片加载器
        imagePicker.setShowCamera(false); // 显示拍照按钮
        imagePicker.setSelectLimit(1);
        imagePicker.setCrop(false); // 允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(false); // 是否按矩形区域保存

        mt3 = (Image) findComponentById(ResourceTable.Id_t3);
        mt1 = (TextField) findComponentById(ResourceTable.Id_t1);
        mt2 = (TextField) findComponentById(ResourceTable.Id_t2);
        Text fb = (Text) findComponentById(ResourceTable.Id_fb);
        Image ret=(Image)findComponentById(ResourceTable.Id_return_img);
        ret.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                present(new HomeFraction(),intent);
            }
        });
        mt3.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.xijing.xinyun")
                        .withAbilityName(ImageGridAbility.class.getName())
                        .build();
                Intent intent = new Intent();
                intent.setOperation(operation);
                startAbilityForResult(intent, REQUEST_CODE_CHOOSE);
            }
        });
        fb.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mt1.getText().toString().isEmpty()) {
                    new ToastDialog(getAbility())
                            .setText("标题不能为空，请检查")
                            .show();
                    return;
                } else if (mt2.getText().toString().isEmpty()) {
                    new ToastDialog(getAbility())
                            .setText("内容不能为空，请检查")
                            .show();
                    return;
                } else if (imagepath.isEmpty()) {
                    new ToastDialog(getAbility())
                            .setText("请选择趣图")
                            .show();
                }

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");


                File dataDir = new File(getAbility().getDataDir().toString());
                if (!dataDir.exists()) {
                    dataDir.mkdirs();
                }

                // 构建目标文件
                File targetFile = new File(Paths.get(dataDir.toString(), imagename).toString());


                DataAbilityHelper dp = DataAbilityHelper.creator(getAbility());
                FileDescriptor fddd = new FileDescriptor();
                try {
                    fddd = dp.openFile(Uri.parse(imagepath), "r");//根据Uri打开文件
                    FileInputStream fileInputStream = new FileInputStream(fddd);
                    inputstreamtofile(fileInputStream, targetFile);
                    ImageSource imageSource = ImageSource.create(targetFile, null);
                    Size size = imageSource.getImageInfo().size;
                    Compressor compressor = new Compressor();
                    Compression compression = new Compression();
                    compression.resolution(size.width, size.height);
                    compression.quality(50);
                    compression.format(CompressFormat.JPEG);
                    compression.size(2048, 0, 0);
                    File d = compressor.compress(getContext(), targetFile, compression);
                    String baty = ImageUtils.imageToBase64(d.getPath());
                    TbTzRequestBean Tbtz=new TbTzRequestBean();
                    Tbtz.setDizan("0");
                    String time=simpleDateFormat.format(new Date());
                    Tbtz.setBytime(simpleDateFormat.format(new Date()));
                    Tbtz.setByuser(MyApplication.username);
                    Tbtz.setId(0);
                    Tbtz.setTzcontent(mt2.getText().toString().trim());
                    Tbtz.setTzimg(baty.getBytes());
                    Tbtz.setTztitle(mt1.getText().toString().trim());

                    ZZRHttp.postJson(UrlContant.URL+"addTz", new Gson().toJson(Tbtz), new ZZRCallBack.CallBackString() {
                        @Override
                        public void onFailure(int i, String s) {
                            new ToastDialog(FbAbilitySlice.this)
                                    .setText("请检查网络连接")
                                    .show();
                        }

                        @Override
                        public void onResponse(String s) {
                            TbFourmList db_user1 = new Gson().fromJson(s, TbFourmList.class);
                            if (db_user1.getCode().equals("200")){
                                myEventHandler.sendEvent(0);
                            } else {
                                myEventHandler.sendEvent(1);

                            }
                        }
                    });
                } catch (Exception e) {

                } finally {
                    return;
                }

            }
        });
    }


    public void inputstreamtofile(InputStream ins, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
